<?php
namespace common\components\autoLoad;

use backend\models\AppModules;
use yii\base\Event;
use yii\db\Query;

/**
 * 自动加载模块
 * Class Load
 * @package modules
 */
class Load
{
    /**
     * run
     * @param Event $event
     * @throws \Exception
     */
    public static function run(Event $event)
    {
        try {
            /** @var $application \yii\base\Application */
            $application = $event->sender;
            $type =explode('\\',$application->controllerNamespace)[0]??'';

            if(empty($type))
                return;

            $appModules = cache()->getOrSet(AppModules::CACHE_KEY,function (){
                return (new Query())->select(['id','class','config','type'])
                    ->from(['app_modules'])
                    ->where(['status'=>1])->all();
            });

            foreach ($appModules as $appModule){
                if($appModule['type'] == $type && !$application->hasModule($appModule['id'])){
                    $config = json_decode($appModule['config'],1);
                    $config['class'] = $appModule['class'];
                    $application->setModule($appModule['id'],$config);
                }
            }
        }catch (\Exception $e){
            if(YII_DEBUG){
                throw new \Exception($e->getMessage());
            }else{
                Log::error('数据库加载模块错误.',exceptionFormat($e,false));
            }
        }
    }
}